package rpc

import (
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
	"log"
	"vben-api/config"
	"vben-common/discovery"
	"vben-common/logs"
	buttonServiceV1 "vben-grpc-common/vben-admin/types/button.service.v1"
	interfaceServiceV1 "vben-grpc-common/vben-admin/types/interface.service.v1"
	menuService "vben-grpc-common/vben-admin/types/menu.service.v1"
	roleServiceV1 "vben-grpc-common/vben-admin/types/role.service.v1"
	systemServiceV1 "vben-grpc-common/vben-admin/types/system.service.v1"
	userServiceV1 "vben-grpc-common/vben-admin/types/user.service.v1"
)

// SystemServiceClient 用于与系统服务进行通信的gRPC客户端
var SystemServiceClient systemServiceV1.SystemServiceClient
var MenuServiceClient menuService.MenuServiceClient
var RoleServiceClient roleServiceV1.RoleServiceClient
var UserServiceClient userServiceV1.UserServiceClient
var InterfaceServiceClient interfaceServiceV1.InterfaceServiceClient
var ButtonServiceClient buttonServiceV1.ButtonServiceClient

func InitRpcClient() {
	// 使用配置的etcd地址创建一个解析器
	etcdResolver := discovery.NewResolver(config.C.EtcdConfig.Addrs, logs.LG)
	// 注册解析器，以便gRPC库可以使用它来解析服务地址
	resolver.Register(etcdResolver)

	// 建立到vben-admin服务的gRPC连接，使用不安全的凭据（适用于开发环境）
	// ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	conn, err := grpc.NewClient("etcd:///vben-admin", opts...)
	// conn, err := grpc.Dial("etcd:///vben-admin", grpc.WithTimeout(10*time.Second), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		// 如果连接失败，记录错误并终止程序
		log.Fatalf("grpc connect fail: %v\n", err)
	}
	// 使用建立的连接创建一个SystemServiceClient实例，用于与系统服务进行通信
	SystemServiceClient = systemServiceV1.NewSystemServiceClient(conn)
	MenuServiceClient = menuService.NewMenuServiceClient(conn)
	RoleServiceClient = roleServiceV1.NewRoleServiceClient(conn)
	UserServiceClient = userServiceV1.NewUserServiceClient(conn)
	InterfaceServiceClient = interfaceServiceV1.NewInterfaceServiceClient(conn)
	ButtonServiceClient = buttonServiceV1.NewButtonServiceClient(conn)
}
